package com.zhentao.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhentao.common.Result;
import com.zhentao.entity.Users;
import com.zhentao.mapper.UsersMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 用户管理控制器
 */
@RestController
@RequestMapping("/admin/user")
@CrossOrigin(origins = "*")
public class UserController {
    
    @Autowired
    private UsersMapper usersMapper;
    
    /**
     * 用户列表（分页）
     */
    @GetMapping("/list")
    public Result<Map<String, Object>> list(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) Integer gender,
            @RequestParam(required = false) Integer vipLevel,
            @RequestParam(required = false) String keyword) {
        
        try {
            Page<Users> pageInfo = new Page<>(page, pageSize);
            QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
            
            // 性别筛选
            if (gender != null) {
                queryWrapper.eq("gender", gender);
            }
            
            // VIP等级筛选
            if (vipLevel != null) {
                queryWrapper.eq("vip_level", vipLevel);
            }
            
            // 关键词搜索
            if (keyword != null && !keyword.isEmpty()) {
                queryWrapper.and(wrapper -> wrapper
                        .like("nickname", keyword)
                        .or()
                        .like("phone", keyword));
            }
            
            // 按创建时间倒序
            queryWrapper.orderByDesc("create_time");
            
            Page<Users> result = usersMapper.selectPage(pageInfo, queryWrapper);
            
            Map<String, Object> data = new HashMap<>();
            data.put("list", result.getRecords());
            data.put("total", result.getTotal());
            data.put("page", page);
            data.put("pageSize", pageSize);
            
            return Result.success(data);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询失败：" + e.getMessage());
        }
    }
    
    /**
     * VIP用户列表
     */
    @GetMapping("/vip/list")
    public Result<Map<String, Object>> vipList(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        
        try {
            Page<Users> pageInfo = new Page<>(page, pageSize);
            QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
            
            // 只查询VIP用户
            queryWrapper.gt("vip_level", 0);
            queryWrapper.orderByDesc("vip_end_time");
            
            Page<Users> result = usersMapper.selectPage(pageInfo, queryWrapper);
            
            Map<String, Object> data = new HashMap<>();
            data.put("list", result.getRecords());
            data.put("total", result.getTotal());
            data.put("page", page);
            data.put("pageSize", pageSize);
            
            return Result.success(data);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询失败：" + e.getMessage());
        }
    }
    
    /**
     * 用户详情
     */
    @GetMapping("/detail/{userId}")
    public Result<Users> detail(@PathVariable Integer userId) {
        try {
            Users user = usersMapper.selectById(userId);
            if (user == null) {
                return Result.error("用户不存在");
            }
            return Result.success(user);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询失败：" + e.getMessage());
        }
    }
    
    /**
     * 更新用户状态
     */
    @PutMapping("/update/{userId}")
    public Result<String> updateStatus(@PathVariable Integer userId, @RequestBody Map<String, Object> params) {
        try {
            Users user = usersMapper.selectById(userId);
            if (user == null) {
                return Result.error("用户不存在");
            }
            
            if (params.containsKey("status")) {
                user.setStatus((Integer) params.get("status"));
                usersMapper.updateById(user);
            }
            
            return Result.success("更新成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("更新失败：" + e.getMessage());
        }
    }
    
    /**
     * 用户统计
     */
    @GetMapping("/stats")
    public Result<Map<String, Object>> stats() {
        try {
            // 总用户数
            Long totalUsers = usersMapper.selectCount(null);
            
            // VIP用户数
            QueryWrapper<Users> vipWrapper = new QueryWrapper<>();
            vipWrapper.gt("vip_level", 0);
            Long vipUsers = usersMapper.selectCount(vipWrapper);
            
            // 男性用户数
            QueryWrapper<Users> maleWrapper = new QueryWrapper<>();
            maleWrapper.eq("gender", 1);
            Long maleUsers = usersMapper.selectCount(maleWrapper);
            
            // 女性用户数
            QueryWrapper<Users> femaleWrapper = new QueryWrapper<>();
            femaleWrapper.eq("gender", 2);
            Long femaleUsers = usersMapper.selectCount(femaleWrapper);
            
            Map<String, Object> stats = new HashMap<>();
            stats.put("totalUsers", totalUsers);
            stats.put("vipUsers", vipUsers);
            stats.put("maleUsers", maleUsers);
            stats.put("femaleUsers", femaleUsers);
            
            return Result.success(stats);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("统计失败：" + e.getMessage());
        }
    }
}

